@echo off
REM 阿里云服务器快速部署脚本 (Windows版本)
REM 使用方法: deploy_to_aliyun.bat 您的服务器IP

if "%1"=="" (
    echo 使用方法: %0 ^<服务器IP^>
    echo 示例: %0 123.456.789.123
    pause
    exit /b 1
)

set SERVER_IP=%1
set PROJECT_DIR=/opt/patient-management

echo 开始部署到阿里云服务器: %SERVER_IP%

REM 1. 上传文件到服务器
echo 正在上传文件...
scp websocket_server.py root@%SERVER_IP%:/tmp/
scp requirements.txt root@%SERVER_IP%:/tmp/

REM 2. 在服务器上执行部署命令
echo 正在配置服务器环境...
ssh root@%SERVER_IP% "apt update && apt upgrade -y"
ssh root@%SERVER_IP% "apt install python3 python3-pip python3-venv -y"
ssh root@%SERVER_IP% "mkdir -p %PROJECT_DIR%"
ssh root@%SERVER_IP% "cd %PROJECT_DIR% && python3 -m venv venv"
ssh root@%SERVER_IP% "cd %PROJECT_DIR% && source venv/bin/activate && mv /tmp/websocket_server.py ./ && mv /tmp/requirements.txt ./ && pip install -r requirements.txt"

REM 创建系统服务
echo 正在创建系统服务...
ssh root@%SERVER_IP% "cat > /etc/systemd/system/websocket-server.service << 'EOF'
[Unit]
Description=Patient Management WebSocket Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=%PROJECT_DIR%
Environment=PATH=%PROJECT_DIR%/venv/bin
ExecStart=%PROJECT_DIR%/venv/bin/python websocket_server.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF"

REM 启动服务
ssh root@%SERVER_IP% "systemctl daemon-reload"
ssh root@%SERVER_IP% "systemctl enable websocket-server"
ssh root@%SERVER_IP% "systemctl start websocket-server"

REM 创建备份脚本
echo 正在创建备份脚本...
ssh root@%SERVER_IP% "cat > /opt/backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR=/opt/backups
DATE=\$(date +%%Y%%m%%d_%%H%%M%%S)
mkdir -p \$BACKUP_DIR
tar -czf \$BACKUP_DIR/websocket-server_\$DATE.tar.gz %PROJECT_DIR%/
find \$BACKUP_DIR -name \"websocket-server_*.tar.gz\" -mtime +7 -delete
echo \"备份完成: websocket-server_\$DATE.tar.gz\"
EOF"

ssh root@%SERVER_IP% "chmod +x /opt/backup.sh"

REM 设置定时备份
ssh root@%SERVER_IP% "(crontab -l 2>/dev/null; echo \"0 2 * * * /opt/backup.sh\") | crontab -"

echo 部署完成！
echo.
echo 下一步操作：
echo 1. 修改Android客户端中的服务器IP为: %SERVER_IP%
echo 2. 重新编译APK: gradlew.bat assembleRelease
echo 3. 测试连接是否正常
echo.
echo 服务器管理命令：
echo 查看状态: ssh root@%SERVER_IP% "systemctl status websocket-server"
echo 查看日志: ssh root@%SERVER_IP% "journalctl -u websocket-server -f"
echo 重启服务: ssh root@%SERVER_IP% "systemctl restart websocket-server"
echo.
pause 